import axios from 'axios';

const httpHander = function (resolve, response, reject) {
  const res = response.data
  res.code = 404
    if (res.code !== 0) {
      if (res.code === 401) {
        this.$router.replace('/Login')
        return false
      }
      this.$message.error(res.msg);
      reject()
      return false
    }
    resolve(res.data)
}

export default {
  install (Vue, options) {

    axios.interceptors.request.use(conf => {
      conf.headers.token = options.token;
      conf.headers.uid = options.userId;
      conf.headers['If-Modified-Since'] = 0
      return conf;
    }, err => {
      return Promise.reject(err);
    })

    Vue.prototype.http2Get = function (url, params) {
      return new Promise((resolve, reject) => {
        axios.get(url, { params }).then((response) => { httpHander.call(this, resolve, response, reject) }).catch((err) => {
          reject(err)
        })
      })
    }
  }
}

/* 用法：

this.http2Get().then().catch()

catch里面的函数会在报500或者 code 不为1 的情况下运行
*/